package com.flyqiu.form.extensions.convert.mapping;

import com.alibaba.fastjson2.JSONArray;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class AvueCheckBoxMapper extends AvueBaseDicDataMapper {
    public static final String MAPPER_TYPE = "checkbox";

    @Override
    public Object labelToValue(String label) {
        List<String> dataList = valueDataList(label);
        List<Object> result = new ArrayList<>();
        for (String item : dataList) {
            Object o = super.labelToValue(item);
            result.add(o);
        }
        return result;

    }

    @Override
    public Object valueToLabel(Object value) {
        if (value == null) return "";
        String valStr = String.valueOf(value);
        List<String> dataList = valueDataList(valStr);
        List<String> result = new ArrayList<>();
        for (String item : dataList) {
            String label = (String) super.valueToLabel(item);
            result.add(label);
        }
        return String.join(",", result);
    }

    private List<String> valueDataList(String val) {
        if (strIsJson(val)) {
            return JSONArray.parseArray(val, String.class);
        }
        if (val.contains(",")) {
            return Arrays.stream(val.split(",")).collect(Collectors.toList());
        }
        ArrayList<String> result = new ArrayList<>();
        result.add(val);
        return result;
    }
}
